<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { useGlobalStore } from '@/store/global'
import { useAuthStore } from '@/store/auth'
import { useEnvStore } from './store/env'
import { initRangersSDK } from './dataReport/dataReportUtil'
import $$Rangers from '@datarangers/sdk-mp'
import { WebsocketManager } from './utils/socket/WebsocketManager'
import { checkVersion } from '@/i18n/index'
import { setPairingDetail } from './utils/waitforpairing'
import i18n from '@/i18n'
import { specialSceneJumpOnLaunch } from '@/utils/loading'
import { resetPermanentInfo } from './api/deviceMessageSubscribe'
import { getLatestPage } from './utils/mpHelper'
import { TrackType, trackEvent } from './dataReport/tracks'
import { safeTrack } from './dataReport/dataReportUtil'

const globalStore = useGlobalStore()
const envStore = useEnvStore()
const authStore = useAuthStore()
const sceneObj = {
  sceneNumber: '999',
  sceneName: '来自HC',
}

let switchNetBack: boolean = false
function onNetworkStatusChange(res: any): void {
  if (['2g', '3g', '4g', 'wifi'].includes(res.networkType)) {
    console.log('onNetworkStatusChange...')
    if (getLatestPage() !== null) {
      WebsocketManager.instance.connectWebsocket()
    }
  }
  //取反满足条件,跳转已经写好的网络异常页面
  if (!res.isConnected) {
    switchNetBack = true
    uni.navigateTo({ url: '/pages/navigator/networkError/networkError' })
    // uni.navigateTo({ url: '/pages/pairing/scanErroreTip/scanErroreTip' })
  } else {
    // 网络恢复后回跳
    if (switchNetBack) {
      uni.navigateBack()
      switchNetBack = false
    }
  }
}

onLaunch((options) => {
  console.log('onLaunch', options)
  uni.onNetworkStatusChange(onNetworkStatusChange)
  authStore.initStoredData()
  globalStore.setLaunchOptions(options)

  // 初始化火山SDK
  initRangersSDK()
  //特殊scene处理
  specialSceneJumpOnLaunch(options)

  authStore.loadOpenAndUnionId()

  envStore.loadAgreement()
  // 更新i18n文件
  checkVersion().then((res) => {
    i18n.global.mergeLocaleMessage('zh_CN', res.zh_CN)
    i18n.global.mergeLocaleMessage('en', res.en)
  })
  // 增加启动埋点
  safeTrack(() => {
    trackEvent('hc_on_launch', { options: options }, TrackType.BusinesssScene)
  })
})

onShow((options: any) => {
  console.log('onShow', options)
  // 增加onShow生命周期埋点
  safeTrack(() => {
    trackEvent('hc_on_show', { options: options }, TrackType.BusinesssScene)
  })

  updateApp()
  setPairingDetail(options, sceneObj)

  globalStore.setLaunchOptions(options)
  envStore.loadSystemInfo()
  let scene = decodeURIComponent(options.scene)
  if (options.query && options.query.msg_uuid) {
    globalStore.msg_uuid = options.query.msg_uuid
  }

  globalStore.sceneNumber = sceneObj.sceneNumber
  globalStore.sceneName = sceneObj.sceneName
  $$Rangers.config({
    hc_msg_uuid: globalStore.msg_uuid,
    hc_sceneNumber: globalStore.sceneNumber,
    hc_sceneName: globalStore.sceneName,
  })

  // 判断用户是否重新加载小程序
  let isNewUser = uni.getStorageSync('isNewUser')
  if (!isNewUser && authStore.isLogin) {
    resetPermanentInfo()
    uni.setStorageSync('isNewUser', true)
  }
  if (getLatestPage() !== null) {
    WebsocketManager.instance.connectWebsocket()
  }
})

onHide(() => {
  console.log('application onHide')
  // onHide 设置重新获取 Token
  authStore.needRefreshToken = true
})
function updateApp() {
  const updateManager = uni.getUpdateManager()
  updateManager.onCheckForUpdate((res) => {
    // 请求完新版本信息的回调
    if (res.hasUpdate) {
      uni.showLoading({
        title: '更新下载中...',
      })
    }
  })
  updateManager.onUpdateReady(function () {
    setTimeout(() => {
      uni.hideLoading()
      uni.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        },
      })
    }, 2000)
  })
  updateManager.onUpdateFailed(function () {
    // 新的版本下载失败
    setTimeout(() => {
      uni.hideLoading()
      uni.showToast({
        title: '下载失败...',
        icon: 'none',
      })
    }, 2000)
  })
}
</script>

<style lang="less">
@import '@/styles/switch.less';
@import '@/styles/progressStyle.less';
@import '@/styles/custonModal.less';
page {
  --primary-vector: 64, 141, 242;
  --primary-color: rgb(var(--primary-vector));
  /* --primary-color: #408df2; */

  --dark-vector: 45, 55, 70;
  --dark-color: rgb(var(--dark-vector));
  /* --dark-color: #2d3746; */

  --warning-vector: 255, 204, 102;
  --warning-color: rgb(var(--warning-vector));
  /* --warning-color: #ffcc66; */

  --danger-vector: 255, 69, 58;
  --danger-color: rgb(var(--danger-vector));
  /* --danger-color: #ff453a; */

  color: var(--dark-color);
}
.safe-area-top {
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
}
.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.wx-switch-input {
  .generalSwitch();
}
</style>
